using Dapper;
using MediatR;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ERP.SalesManagement.H;
using System.Data;
using static RBAC.ErrorCode.APIEnums;

namespace RBAC.Write.Api.Application.Handler.ERP.SalesManagement
{
    /// <summary>
    /// 批量逻辑删除 发货通知单（Delivery_notice.IsDeleted = true），并同步删除明细
    /// </summary>
    public class BatchDeleteDeliveryNoticeHandler : IRequestHandler<BatchDeleteDeliveryNoticeCommand, APIResult<bool>>
    {
        private readonly IDbConnectionFactory _dbConnectionFactory;

        public BatchDeleteDeliveryNoticeHandler(IDbConnectionFactory dbConnectionFactory)
        {
            _dbConnectionFactory = dbConnectionFactory;
        }

        public async Task<APIResult<bool>> Handle(BatchDeleteDeliveryNoticeCommand request, CancellationToken cancellationToken)
        {
            if (request.Ids == null || request.Ids.Count == 0)
            {
                return new APIResult<bool> { Code = Error, Msg = "参数为空：未提供要删除的Id集合", Data = false };
            }

            IDbConnection? conn = null;
            IDbTransaction? tran = null;

            try
            {
                conn = _dbConnectionFactory.CreateConnection();
                tran = conn.BeginTransaction();

                // 1) 过滤有效的（存在且未删除）
                var validIds = (await conn.QueryAsync<long>(
                    "SELECT Id FROM Delivery_notice WHERE Id IN @Ids AND IsDeleted = 0",
                    new { Ids = request.Ids }, tran)).ToList();

                if (validIds.Count == 0)
                {
                    tran.Rollback();
                    return new APIResult<bool> { Code = Error, Msg = "单据不存在或均已删除", Data = false };
                }

                // 2) 批量逻辑删除主表
                var affected = await conn.ExecuteAsync(
                    "UPDATE Delivery_notice SET IsDeleted = 1 WHERE Id IN @Ids",
                    new { Ids = validIds }, tran);

                if (affected <= 0)
                {
                    tran.Rollback();
                    return new APIResult<bool> { Code = Error, Msg = "删除失败", Data = false };
                }

                // 3) 批量逻辑删除明细表
                await conn.ExecuteAsync(
                    "UPDATE Delivery_notice_item SET IsDeleted = 1 WHERE Delivery_notice_id IN @Ids",
                    new { Ids = validIds }, tran);

                tran.Commit();
                return new APIResult<bool> { Code = Success, Msg = "批量删除成功", Data = true };
            }
            catch (Exception ex)
            {
                try { tran?.Rollback(); } catch { }
                return new APIResult<bool> { Code = Error, Msg = $"删除异常: {ex.Message}", Data = false };
            }
            finally
            {
                try { tran?.Dispose(); } catch { }
                try { conn?.Dispose(); } catch { }
            }
        }
    }
}
